const mongoose = require('mongoose');
const Joi = require('joi');

const articleSchema = new mongoose.Schema({
    title: {
        type: String,
        maxlength: 20,
        minlength: 4,
        required: [true, '请填写文章标题']
    },
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, "请填写作者"]
    },
    publishDate: {
        type: Date,
        default: Date.now
    },
    cover: {
        type: String,
        default: null
    },
    content: {
        type: String,
        required: [true, "请填写内容"]
    }
});

const Article = mongoose.model('Article', articleSchema);

const validateArticle = articleInfo => {
    // 定义对象的验证规则
    // 注意这里不设置required的话，参数是可选的
    const schema = {
        title: Joi.string().min(4).max(20).error(new Error("标题应该为4-20个字符")),
        author: Joi.string().required().error(new Error("作者_id是必须的")),
        publishDate: Joi.date().error(new Error("发布时间需要是时间类型")),
        cover: Joi.object().error(new Error("封面应该是对象类型")),
        content:Joi.string().required().error(new Error("内容是必须的"))
    }

    // npm install joi@14.3.1
    // 这里版本过高报错  Joi.validate is a not function
    // 返回验证结果的Promise对象
    return Joi.validate(articleInfo, schema);
}

module.exports = {
    Article,
    validateArticle
}
